import java.io.*;
import java.util.Scanner;

public class demo13 {
    public static void main(String[] args) {

        //扫描指定目录，并找到名称或内容中包含指定字符的所用普通文件

        Scanner scanner = new Scanner(System.in);
        System.out.println("输入要扫描的目录路径：");
        String str = scanner.nextLine();
        File rootFile = new File(str);
        if(!rootFile.isDirectory()) {
            System.out.println("输入的路径不是目录！");
        }
        System.out.println("输入想要查找的关键字：");
        String dest = scanner.next();

        scanDir(rootFile,dest);
    }

    private static void scanDir(File rootFile, String dest) {
        File[] files = rootFile.listFiles();
        if(files == null) {
            //当前目录没有内容
            return;
        }
        for(File file : files) {
            if(file.isFile()) {
                dealFile(file,dest);
            }else {
                scanDir(file,dest);
            }
        }
    }

    private static void dealFile(File file, String dest) {
        if(file.getName().contains(dest)) {
            System.out.println("文件名包含关键字" + file.getAbsolutePath());
            return;
        }
        //将文件内容读取出来，使用 stringBuilder接收
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader = new FileReader(file)) {
            while(true) {
                char[] date = new char[1024];
                int n = reader.read(date);
                if(n == -1) {
                    break;
                }
                stringBuilder.append(date,0,n);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if(stringBuilder.indexOf(dest) >= 0) {
            System.out.println("文件内容包含关键字" + file.getAbsolutePath());
        }
    }
}
